package gwt.coonay.server;

import gwt.coonay.client.NoteDTO;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.PersistenceException;
import javax.persistence.Query;

import org.apache.log4j.Logger;
import org.springframework.orm.jpa.JpaCallback;
import org.springframework.orm.jpa.JpaTemplate;
import org.springframework.dao.DataAccessException;

public class JpaNoteDao {
	private JpaTemplate jpaTemplate;
	static Logger log = Logger.getLogger(JpaNoteDao.class);

	public void setEntityManagerFactory(EntityManagerFactory emf) {
		this.jpaTemplate = new JpaTemplate(emf);
	}
	
	
	public List<NoteDTO> streamResult(List<Note> result)
	{
		List<NoteDTO> notes = new ArrayList<NoteDTO>();
		for (Note note:result ){
			NoteDTO n = Note.newRootInstance(note);
			log.info(note.getGmail()+"!!!"+n.getGmail());
			notes.add(n);
		}		
		return notes;
	}

	@SuppressWarnings("unchecked")
	public Collection<Note> loadAll() throws DataAccessException {
		return (Collection<Note>) this.jpaTemplate.execute(new JpaCallback() {

			public Object doInJpa(EntityManager em) throws PersistenceException {
				
				//Query query = em.createNamedQuery("Note.listAll");
				Query query = em.createQuery("SELECT n FROM gwt.coonay.server.Note n");
				List<Note> result = (List<Note>) query.getResultList();
				log.info("Notes record counts:" + result.size());
				for ( Note n :result )
					log.info(n.toString()+":"+n.getGmail()+":mail2:"+n.mail2);
				// do some further processing with the result list
				return result;
			}
		});
	}
    
	public void create(final Note note) throws DataAccessException {
		this.jpaTemplate.execute(new JpaCallback() {
			public Object doInJpa(EntityManager em) throws PersistenceException {
				
				em.persist(note);
				
				return note;
			}
		});
	}
	
	
	public void nativeCreate(final Note note) throws DataAccessException {
		this.jpaTemplate.execute(new JpaCallback() {
			public Object doInJpa(EntityManager em) throws PersistenceException {
				EntityTransaction et = em.getTransaction();
				et.begin();
				em.persist(note);
				et.commit();
				return note;
			}
		});
	}
	
}
